<?php

require_once 'hd/Compile.php';
require_once 'cache.php';
class View extends Compile
{
	//分配的变量
	private $vars=[];

	private $compileFile;
	//编译目录
	public $compile_dir = 'compile';

	public $template_dir='tpl';

	public $cache_dir='cache';
	//模板文件
	private $tpl;

	//分配数据
	public function assign()
	{
		$args= func_get_args();
		switch (count($args)) {
			case 1:
				foreach($args[0] as $name=>$value)
				{
					$this->vars[$name]=$value;	
				}
				break;
			
			case 2:
				$this->vars[$args[0]]=$args[1];
				break;
		}
		
		return $this;
	}

	public function display($tpl,$expire = 0)
	{
		$cache = new Cache($this->cache_dir);
		//缓存名
		$cacheName = md5($_SERVER['REQUEST_URI']);
		if($con = $cache->get($cacheName))
		{
			//缓存有效
			echo $con;
		}
		else
		{

			$this->tpl = $this->template_dir.'/'.$tpl;

			//编译文件
			$this->compileFile = $this->compile_dir.'/'.md5($this->tpl).'.php';

			//验证编译文件，编译文件失效时重新编译
			if($this->checkCompileFile()){
				//编译文件
				$this->compile();
			}
			$hd['get']=$_GET;
			//分配变量
			extract($this->vars);

			//利用缓冲区特点获取响应给客户端的内容
			ob_start();
			require $this->compileFile;
			$con = ob_get_clean();

			
			if($expire>0)
			{
				$cache->set($cacheName,$con,$expire);
			}

			echo $con;
		}
	}

	public function isCache()
	{
		$cache = new Cache($this->cache_dir);
		return $cache->has(md5($_SERVER['REQUEST_URI']));
	}
	/**
	 * 验证编译文件
	 * @return [type] [description]
	 */
	private function checkCompileFile()
	{
		return !is_file($this->compileFile) ||filemtime($this->tpl)>filemtime($this->compileFile);
	}

	//编译模板
	private function compile()
	{
		$content = file_get_contents($this->tpl);
		$content = $this->compileTpl($content);

		//写入编译文件
		file_put_contents($this->compileFile, $content);
	}

	public function __set($name,$value)
	{
		$this->vars[$name]=$value;
	}	

	
}







